package io.github.maojian.hash;

import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: jian.mao
 * @Date: 2022-07-07 09:01
 * @Description: https://leetcode.cn/problems/replace-words/
 */
public class Q648 {
    public String replaceWords(List<String> dictionary, String sentence) {
        Map<String, Integer> map = new HashMap<>();
        for (String s : dictionary) {
            map.put(s, s.length());
        }
        String[] sentences = sentence.split(" ");
        int length = sentences.length;
        StringBuilder stringBuilder = new StringBuilder();
        boolean flag;
        for (int i = 0; i < length; i++) {
            String curSentence = sentences[i];
            flag = true;
            for (int j = 1; j <= curSentence.length(); j++) {
                String curDic = curSentence.substring(0, j);
                if (map.containsKey(curDic) && map.get(curDic) == j) {
                    stringBuilder.append(curDic);
                    flag = false;
                    break;
                }
            }
            if (flag) {
                stringBuilder.append(curSentence);
            }
            if (i < length - 1) {
                stringBuilder.append(" ");
            }
        }
        return stringBuilder.toString();
    }

    @Test
    public void test() {
        String[] dictionary = new String[]{"cat", "bat", "rat"};
        List<String> dictionaryList = Arrays.asList(dictionary);
        String sentence = "the cattle was rattled by the battery";
        System.out.println(replaceWords(dictionaryList, sentence));
    }

    @Test
    public void test01() {
        String[] dictionary = new String[]{"a", "aa", "aaa", "aaaa"};
        List<String> dictionaryList = Arrays.asList(dictionary);
        String sentence = "a a a aaaaaa aaa aaa aaa aaaaaaaaaa bbb baba a";
        System.out.println(replaceWords(dictionaryList, sentence));
    }
}
